package com.xinlong.shop.core.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinlong.shop.core.order.entity.Cart;
import com.xinlong.shop.core.order.entity.dto.CartDTO;
import com.xinlong.shop.core.order.mapper.CartDTOMapper;
import com.xinlong.shop.core.order.mapper.CartMapper;
import com.xinlong.shop.core.order.service.ICartService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;

import java.util.List;

/**
 * <p>
 * 购物车表 服务实现类
 * </p>
 *
 * @author Sylow
 * @since 2023-04-21
 */
@Service
public class CartServiceImpl extends ServiceImpl<CartMapper, Cart> implements ICartService {

    private final CartDTOMapper cartDTOMapper;

    public CartServiceImpl(CartDTOMapper cartDTOMapper) {
        this.cartDTOMapper = cartDTOMapper;
    }

    @Override
    public void update(Cart cart, Integer id) {
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        this.update(cart, updateWrapper);
    }
    @Override
    public void delete(Integer id) {
        UpdateWrapper<Cart> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("id", id);
        this.remove(deleteWrapper);
    }

    @Override
    public void addCart(Cart cart) {
        // 先查询是否已经加入购物车了
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("goods_id", cart.getGoodsId());
        queryWrapper.eq("member_id", cart.getMemberId());
        Cart cartTemp = this.getOne(queryWrapper);

        if (cartTemp == null) {
            cart.setUpdateTime(DateUtil.currentSeconds());
            cart.setCreateTime(DateUtil.currentSeconds());
            this.save(cart);
        } else {
            cartTemp.setUpdateTime(DateUtil.currentSeconds());
            cartTemp.setNum(cartTemp.getNum() + 1);
            this.update(cartTemp, cartTemp.getId());
        }

    }

    @Override
    public List<CartDTO> findListByMemberId(Integer memberId) {
        return this.cartDTOMapper.findCartList(memberId);
    }

    @Override
    public void updateNum(Integer id, Integer memberId, Integer num) {
        UpdateWrapper<Cart> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", id);
        updateWrapper.eq("member_id", memberId);
        updateWrapper.set("num", num);
        this.update(updateWrapper);
    }

    @Override
    public void delete(Integer id, Integer memberId) {
        UpdateWrapper<Cart> deleteWrapper = new UpdateWrapper<>();
        deleteWrapper.eq("id", id);
        deleteWrapper.eq("member_id", memberId);
        this.remove(deleteWrapper);
    }


}
